<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="maximum-scale=1.0,minimum-scale=1.0,user-scalable=0,width=device-width,initial-scale=1.0" />
    <meta name="format-detection" content="telephone=no,email=no,date=no,address=no">
    <title>礼包领取</title>
    <link rel="stylesheet" href="../../icon/iconfont.css">
    <link rel="stylesheet" type="text/css" href="../../css/api.css" />
    <link rel="stylesheet" type="text/css" href="../../css/style.css" />
    <link rel="stylesheet" href="../../css/aui.css">
    <link rel="stylesheet" href="../../css/frame0/gift-bag-lingqu.css">
    <style>
      .giftBag{
        height: 100%;
      }
      .shadowBox{
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background-color: rgba(0,0,0,.3);
        z-index: 99;
        display: none
      }
      .selectBox{
        width: 14rem;
        height: 8rem;
        background-color: #fff;
        margin-left: 50%;
        margin-top: 90%;
        transform: translate(-50%,-50%);
      }
      .selectHead{
        height: 2rem;
        line-height: 2rem;
        border-bottom: 1px solid #eee;
        text-align: center;
      }
      .selectContent{
        height: 4rem;
        display: flex;
        align-items:center;
        justify-content: center;
      }
      .aui-list-item-inner input{
        transform: scale(0.8);

      }
      .aui-radio:checked{
        background-color: #ecbb6f;
        border: #ecbb6f;
      }
      .selectFoot{
        height: 2rem;
        line-height: 2rem;
        display: flex;
        justify-content: space-between;
      }
      .selectFoot div{
        width: 50%;
        text-align: center;
        border-top: 1px solid #eee;
      }
      .selectFoot .left{
        border-right: 1px solid #eee;
      }
    </style>
</head>

<body style="height:100%">
  <div class="giftBag">
    <!-- 头部 -->
    <header>
      <span class="iconfont icon-fanhui" onClick="api.closeWin()"></span>
      <span>礼包</span>
    </header>
    <!-- 卡券区域 -->
    <div class="content" id="content"></div>
    <!-- 选择付款方式提示框 -->
    <div class="shadowBox">
      <div class="selectBox">
          <div class="selectHead">选择支付方式</div>
          <div class="selectContent">
            <div class="aui-list-item-inner">
              <label>微信 <input class="aui-radio" type="radio" name="radio2" checked value="1"></label>
              <label>支付宝 <input class="aui-radio" type="radio" name="radio2" value="2"></label>
              <label>余额 <input class="aui-radio" type="checkbox" name="radio" value="1" checked></label>
            </div>
          </div>
          <div class="selectFoot">
            <div class="left" onclick="closeBtn(this)">取消</div>
            <div class="right" onclick="payBtn(this)">确认</div>
          </div>
      </div>
    </div>
  </div>
</body>
<script type="text/javascript" src="../../script/jquery-3.3.1.js"></script>
<script type="text/javascript" src="../../script/api.js"></script>
<script type="text/javascript" src="../../script/dns.js"></script>
<script type="text/javascript" src="../../script/aui-toast.js"></script>
<script type="text/javascript" src="../../script/aui-dialog.js" ></script>
<script type="text/javascript" src="../../lib/artTemplate/template.js"></script>
<script type="text/html" id="getbag">
  {{each items as value index}}
    <div class="couponList">
      <div class="couponImg">
        <img src="{{value.merchant.img.url}}" alt="">
      </div>
      <div class="couponCenter">
        <p>{{value.merchant.title}}</p>
        <p>{{value.title}}</p>
        {{if value.limit_time_type==1}}
          <p>有效期：{{value.day.str}}</p>
        {{/if}}
        {{if value.limit_time_type==2}}
          <p>有效期：{{value.start_time}}至{{value.end_time}}</p>
        {{/if}}
      </div>
      <div class="couponBtn">
        <button class="btn_conversion" onclick="getCoupon({{value.id}},this)">领取</button>
      </div>
    </div>
  {{/each}}
</script>
<script type="text/html" id="getcouponBag">
  {{each items as value index}}
  <div class="couponList getCoupon">
    <div class="couponImg">
      <img src="../../image/applogo_2.png" alt="">
    </div>
    <div class="couponCenter">
      <div class="head">￥{{value.price}}<text attrList="{{index}}" onclick="openCoupon(this)">(点击查看)</text></div>
      <div class="foot">{{value.title}}</div>
    </div>
    <div class="couponBtn2">
      <button class="btn_conversion2" onclick="couponPay({{value.price}},{{value.id}})">卡包购买</button>
    </div>
  </div>
  {{/each}}
</script>
<script>
    apiready = function() {
      getbagList();
    }
    var toast = new auiToast({});
    var dialog = new auiDialog({});
    function getbagList() {
      var token = localStorage.getItem("token");
      var current_merchant_id = api.pageParam.merchantid;  //扫码支付--跳转到卡券页面（附带的商家id） id-存在：只展示该商家卡券，否则全部显示
        if(!current_merchant_id){
          current_merchant_id == ''
        }
      $.ajax({
        type:"get",
        data:{
          action:1,
          merchid:current_merchant_id
        },
        beforeSend: function(request) {
            request.setRequestHeader("token", token);
        },
        url:dns+"coupon/read",
        success:function(res){
          // console.log(JSON.stringify(res));
          var html = template("getbag",{"items":res.data});
          document.getElementById("content").innerHTML = html;
          $.ajax({
            type:"get",
            dataType:'json',
            beforeSend: function(request) {
                request.setRequestHeader("token", token);
            },
            url:dns+"coupon/bag",
            success:function (res2) {
              // console.log(JSON.stringify(res2));
              if(res2.status == 1){
                var html = template("getcouponBag",{"items":res2.data});
                $("#content").append(html);
              }
              if(res2.status == 0 && res.count == 0){
                var html = "<p style='text-align:center;font-size:1rem;color:#D39B51;margin:50% auto;'>该商家暂无卡券可领取！</p>";
                document.getElementById("content").innerHTML = html;
              }
            }
          })
        }
      })
    }
    function getCoupon(coupon_id,e) {//卡包领取
      $(e).css("disabled","disabled")
      $(e).css("background-color","#ccc").css("color","#fff").text("已领取");
      var token = localStorage.getItem("token");
      var that = $(e);
      $.ajax({
        type:"post",
        data:{
          coupon_id:coupon_id,
          type:1
        },
        beforeSend: function(request) {
            request.setRequestHeader("token", token);
        },
        url:dns+"coupon/receive",
        success:function(res){
          // console.log(JSON.stringify(res));
          that.attr("disabled","disabled");
          toast.success({
            title:res.msg,
            duration:1500
          });
        },
        error:function(err){
          var json = JSON.parse(err.responseText)
          toast.fail({
            title:json.msg,
            duration:1500
          });
        }
      });
    }
    function openCoupon(e) {//卡包查看
      // console.log(list);
      var index = $(e).attr("attrList");
      api.openWin({
          name: 'couponPay',
          url: './couponPay.html',
          bgColor: '#f1f1f1',
          pageParam: {//页面代参数
              index: index
          },
          rect: {
              x: 0,
              y: 25,
              w: api.winWidth,
              h: api.winHeight
          }
      });
    }
    function couponPay(total,id) {//卡券包购买
      dialog.alert({
          title:"提示",
          msg:'您确定要购买当前卡包吗?',
          buttons:['取消','确定']
      },function(ret){
          if(ret){
            console.log(JSON.stringify(ret));
            if(ret.buttonIndex == 2){//用户点击确定
              $(".shadowBox").css("display","block");
              $("body,html").css({"overflow":"hidden"});
              $(".right").attr("total",total);
              $(".right").attr("m_id",id);
            }
          }
      })
    }
    function closeBtn(e) {//用户点击取消选择方式
      $(e).parent().parent().parent().css("display","none");
      $("body,html").css({"overflow":"visible"});
    }
    function payBtn(e) {//用户点击确认选择方式
      $(e).parent().parent().parent().css("display","none");
      $("body,html").css({"overflow":"visible"});
      var type;
      var is_balance;
      var token = localStorage.getItem("token");
      var ifWX = $('input:radio[name="radio2"]:checked').val();
      var ifBalance = $('input:checkbox[name="radio"]:checked').val();
      var total = $(e).attr("total");//金额
      var id = $(e).attr("m_id");//id
      if(ifWX == 1){
        type = 1;//微信支付
      }else{
        type = 2;//微信支付
      };
      if(ifBalance == 1){
        is_balance = 1//选用余额
      }else{
        is_balance = 0//不选用余额
      }
      $.ajax({
        type: 'POST',
        dataType: 'json',
        data: {
          total,
          type,
          is_balance,
          id
        },
        beforeSend: function(request) {
            request.setRequestHeader("token", token);
        },
        url: dns + 'coupon/bag/pay',
        success: function (res) {
          console.log(JSON.stringify(res));
          if(res.status == 2){//余额充足，支付成功
            toast.success({
              title:res.msg,
              duration:1500
            });
          }
          if(res.status == 1){//未选择余额或余额不足，调起微信或支付宝支付
            var dataList = res;
            switch (res.msg) {
              case '微信支付':
                  Wxpay(dataList);
                break;
              case '支付宝支付':
                  AliPay(dataList);
                break;

            }
          }
        }
      })
    }




    // apiCloud微信支付
    function Wxpay(serverData) {
        var wxPay = api.require('wxPay');
        wxPay.config({
            apiKey: serverData.data.apiKey,
            mchId: serverData.data.mchId,
            partnerKey: serverData.data.partnerKey,
            notifyUrl: serverData.data.notifyUrl
        }, function(ret, err) {
            // console.log(JSON.stringify(ret));
            if (ret.status) {
                wxPay.pay({
                    description: serverData.data.description,
                    totalFee: serverData.data.totalFee,
                    tradeNo: serverData.data.tradeNo
                }, function(ret, err) {
                  console.log(JSON.stringify(ret));
                  if (ret.status) {
                    toast.success({
                        title: "购买成功!",
                        duration: 2000
                    });
                  } else {
                    if(err.code == -2){
                      toast.fail({
                          title: "购买失败!",
                          duration: 2000
                      });
                    }
                  }
                });
            } else {
              toast.fail({
                  title: "购买失败!",
                  duration: 2000
              });
            }
        });
    }


    // apiCloud支付宝支付
    function AliPay(serverData) {
        var aliPay = api.require('aliPay');
        aliPay.config({
            partner: serverData.data.partner,
            seller: serverData.data.seller,
            rsaPriKey: serverData.data.rsaPriKey,
            rsaPubKey: serverData.data.rsaPubKey,
            notifyURL: serverData.data.notify_url
        }, function(ret, err) {
            if (ret.status) {
                aliPay.pay({
                    subject: serverData.data.subject,
                    body: serverData.data.body,
                    amount: serverData.data.total_fee,
                    tradeNO: serverData.data.out_trade_no,
                }, function(ret, err) {
                  console.log(JSON.stringify(ret))
                  if(ret.code=="9000"){
                    toast.success({
                        title: "购买成功!",
                        duration: 2000
                    })
                  }else{
                    toast.fail({
                        title: "购买失败!",
                        duration: 2000
                    })
                  }
                })
            } else {
               api.alert({
                 title: '支付结果',
                 msg: err.msg,
                 buttons: ['确定']
               })
          }
        });

    }
</script>

</html>
